package com.htx.zqs.blesmartmask.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.provider.Settings;
import android.support.v4.app.NotificationManagerCompat;
import android.text.TextUtils;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.fanjun.keeplive.KeepLive;
import com.fanjun.keeplive.config.ForegroundNotification;
import com.fanjun.keeplive.config.ForegroundNotificationClickListener;
import com.fanjun.keeplive.config.KeepLiveService;
import com.htx.zqs.blesmartmask.MyApplication;
import com.htx.zqs.blesmartmask.R;
import com.htx.zqs.blesmartmask.bean.EventBean;
import com.htx.zqs.blesmartmask.ui.activity.MainActivity;
import com.htx.zqs.blesmartmask.ui.activity.StartCourseActivity;
import com.htx.zqs.blesmartmask.ui.activity.TestWaterAfterActivity;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.TimeZone;

import cn.addapp.pickers.util.LogUtils;

/**
 * Created by KomoriWu
 * on 2019/2/17.
 */
public class Utils {
    public static boolean checkGPSIsOpen(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager == null)
            return false;
        return locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER);
    }

    public static String utfToString(byte[] data) {
        String str = null;
        try {
            str = new String(data, "utf-8");
        } catch (UnsupportedEncodingException e) {
        }
        return str;

    }

    /* *
     * Convert byte[] to hex string.这里我们可以将byte转换成int，然后利用Integer.toHexString(int)
     *来转换成16进制字符串。
     * @param src byte[] data
     * @return hex string
     */
    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv + "  ");
        }
        return stringBuilder.toString();
    }

    /**
     * byte数组还原为int数组
     *
     * @param data
     * @return
     */
    public int[] byteArray2RgbArray(byte[] data) {
        if (data.length % 4 != 0) {
            return null;
        }
        int[] intarr = new int[data.length / 4];

        int i1, i2, i3, i4;
        for (int j = 0, k = 0; j < intarr.length; j++, k += 4)//j循环int,k循环byte数组
        {
            i1 = data[k];
            i2 = data[k + 1];
            i3 = data[k + 2];
            i4 = data[k + 3];
            if (i1 < 0) {
                i1 += 256;
            }
            if (i2 < 0) {
                i2 += 256;
            }
            if (i3 < 0) {
                i3 += 256;
            }
            if (i4 < 0) {
                i4 += 256;
            }
            intarr[j] = (i1 << 24) + (i2 << 16) + (i3 << 8) + (i4 << 0);//保存Int数据类型转换
        }
        return intarr;
    }

    /**
     * int[]转byte[]
     *
     * @param data
     * @return
     */
    public byte[] byteArray2RgbArray(int[] data) {
        byte[] byteArr = new byte[data.length * 4];
        for (int i = 0; i < data.length; i++) {
            byteArr[i * 4 + 0] = (byte) ((data[i] >> 24) & 0xff);
            byteArr[i * 4 + 1] = (byte) ((data[i] >> 16) & 0xff);
            byteArr[i * 4 + 2] = (byte) ((data[i] >> 8) & 0xff);
            byteArr[i * 4 + 3] = (byte) (data[i] & 0xff);
        }
        return byteArr;
    }

    public static BleDevice getFirstDevice() {
        String firstMac = MySpUtils.getString(MySpUtils.KEY_FIRST_DEVICE);
        List<BleDevice> connBleDeviceList = BleManager.getInstance().getAllConnectedDevice();
        for (BleDevice bleDevice : connBleDeviceList) {
            if (TextUtils.equals(bleDevice.getMac(), firstMac)) {
                return bleDevice;
            }
        }

        if (connBleDeviceList.size() > 0) {
            //过去指定为第一个的已经断开连接，现在重新指定列表第一个为将来的第一个设备
            final BleDevice bleDevice = connBleDeviceList.get(0);
            MySpUtils.putString(MySpUtils.KEY_FIRST_DEVICE, bleDevice.getMac());
            //第一个设备时，才发送
            BleUtils.write(bleDevice, BleUtils.getSerialNumCommand(), new BleWriteCallback() {
                @Override
                public void onWriteSuccess(int current, int total, byte[] justWrite) {
                    MySpUtils.putString(MySpUtils.KEY_FIRST_DEVICE, bleDevice.getMac());
                }

                @Override
                public void onWriteFailure(BleException exception) {

                }
            });
            return bleDevice;
        }

        return null;
    }

    //获取当前测量设备的mac == 面膜神器id
    public static String getCurMac() {
        return MySpUtils.getString(MySpUtils.KEY_FIRST_DEVICE);
    }


    //服务是否存在
    public static boolean isServiceExisted(Context context, String className) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList = activityManager.getRunningServices(Integer.MAX_VALUE);
        if (!(serviceList.size() > 0)) {
            return false;
        }
        for (int i = 0; i < serviceList.size(); i++) {
            ActivityManager.RunningServiceInfo serviceInfo = serviceList.get(i);
            ComponentName serviceName = serviceInfo.service;
            if (serviceName.getClassName().equals(className)) {
                return true;
            }
        }
        return false;
    }

    public static String formatTime(int t1, int t2) {
        String s = "";
        if (t1 < 10) {
            s += "0" + t1 + " : ";
        } else {
            s += t1 + " : ";
        }
        if (t2 < 10) {
            s += "0" + t2;
        } else {
            s += t2;
        }
        return s;
    }

    private static AlertDialog dialog;
    private static RingtoneUtil mRingtoneUtil;

    //课程结束
    public static void EndCourse() {
        final Activity activity = MyApplication.getActivityManager().currentActivity();
        MySpUtils.putBoolean(MySpUtils.KEY_STAR_AUTO_INCREMENT, false);
        MySpUtils.putBoolean(MySpUtils.KEY_END_COURSE_TEST, true);
        EventBusUtil.sendEvent(new EventBean(Constants.EVENT_STOP_COURSE));
        if (dialog != null) {
            if (dialog.isShowing()) {
                dialog.dismiss();
                dialog = null;
            }
        }
        if (mRingtoneUtil != null) {
            mRingtoneUtil.stopShock();
            mRingtoneUtil.stopSound();
            mRingtoneUtil = null;
        }
        mRingtoneUtil = new RingtoneUtil(activity);
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder
                .setCancelable(false)
                .setTitle(activity.getResources().getString(R.string.over))
                .setMessage(activity.getResources().getString(R.string.over_message))
                .setPositiveButton(activity.getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        TestWaterAfterActivity.startAct(activity, Utils.getFirstDevice());
                        mRingtoneUtil.stopShock();
                        mRingtoneUtil.stopSound();
                        if (activity instanceof StartCourseActivity) activity.finish();
                    }
                });
        dialog = builder.create();
        if (!dialog.isShowing()) {
            dialog.show();
        }
        if (dialog.isShowing()) {
            mRingtoneUtil.setSoundAndShock();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mRingtoneUtil.stopShock();
                    mRingtoneUtil.stopSound();
                }
            }, 3 * 9000);
        }
    }

    public static String getCourseName(String type) {
        switch (type) {
            case "B":
                return "嫩白保湿";
            case "C":
                return "深层按摩";
            case "D":
                return "青春痘";
            case "E":
                return "瘦小脸";
            case "F":
                return "紧致拉提";
            default:
                return "油水测试";
        }

    }

    public static String getCourseNameInternal(Context context, String type) {
        switch (type) {
            case "B":
                return context.getString(R.string.course_name_1);
            case "C":
                return context.getString(R.string.course_name_2);
            case "D":
                return context.getString(R.string.course_name_3);
            case "E":
                return context.getString(R.string.course_name_4);
            case "F":
                return context.getString(R.string.course_name_5);
            default:
                return context.getString(R.string.test_message);
        }
    }

    public static String getSexInternal(Context context, String type) {
        switch (type) {
            case "男":
                return context.getString(R.string.order_sex_man);
            case "女":
                return context.getString(R.string.order_sex_woman);
            default:
                return "";
        }
    }

    public static boolean isChinaZones() {
        boolean defaultVaule;
        String time = TimeZone.getDefault().getDisplayName(false, TimeZone.SHORT);
        if (time.contains("GMT+08"))
            defaultVaule = true;
        else
            defaultVaule = false;
        return defaultVaule;
    }

    public static byte[] keyDecode(byte[] bytes0) {
        byte[] bytes = new byte[5];
        //剔除指令头部
        for (int i = 4; i < bytes0.length; i++) {
            bytes[i - 4] = bytes0[i];
        }
        int[] add = new int[]{25, 28, 21, 79, 65};
        int[] reduce = new int[]{17, 14, 56, 45, 45};
        byte[] decodes = new byte[bytes.length];
        for (int i = 0; i < bytes.length; i++) {
            if ((bytes[i] & 0xff) < Integer.parseInt("8f", 16)) {
                decodes[i] = (byte) ~(bytes[i] + add[i]);
            } else {
                decodes[i] = (byte) ~(bytes[i] - reduce[i]);
            }
        }
        byte[] end = new byte[9];
        for (int i = 0; i < 4; i++) {
            end[i] = bytes0[i];
        }
        //后五位向左移1位
        for (int i = 4; i < 9; i++) {
            if (i == 8) {
                end[i] = decodes[0];
            } else {
                end[i] = decodes[i - 4 + 1];
            }

        }
        return end;
    }

    public static void stopKeepLive() {
        startKeepLive("课程已经结束", "点击查看");
    }

    public static void startKeepLive() {
        startKeepLive("课程进行中...", "点击查看");
    }

    private static void startKeepLive(final String title, String description) {
        //定义前台服务的默认样式。即标题、描述和图标
        ForegroundNotification foregroundNotification = new ForegroundNotification(title,
                description, R.mipmap.ic_launcherr22,
                //定义前台服务的通知点击事件
                new ForegroundNotificationClickListener() {

                    @Override
                    public void foregroundNotificationClick(Context context, Intent intent) {
                        intent.setClass(context, MainActivity.class);
                        context.startActivity(intent);
                    }
                });
        //启动保活服务
        KeepLive.startWork(MyApplication.getApplication(), KeepLive.RunMode.ENERGY, foregroundNotification,
                //你需要保活的服务，如socket连接、定时任务等，建议不用匿名内部类的方式在这里写
                new KeepLiveService() {
                    /**
                     * 运行中
                     * 由于服务可能会多次自动启动，该方法可能重复调用
                     */
                    @Override
                    public void onWorking() {

                    }

                    /**
                     * 服务终止
                     * 由于服务可能会被多次终止，该方法可能重复调用，需同onWorking配套使用，如注册和注销broadcast
                     */
                    @Override
                    public void onStop() {

                    }
                }
        );
    }


    public static boolean checkNotifySetting(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return NotificationManagerCompat.from(context).getImportance() != NotificationManager.IMPORTANCE_NONE;
        }
        return NotificationManagerCompat.from(context).areNotificationsEnabled();
    }

    public static void openPermissionSetting(Context context) {
        if (getMeizuFlymeOSFlag().toLowerCase().contains("flyme")) {
            //如果是魅族
            toSetting(context);
            return;
        }
        try {
            Intent localIntent = new Intent();
            localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //直接跳转到应用通知设置的代码：
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                localIntent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
                localIntent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName());
                context.startActivity(localIntent);
                return;
            }
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                localIntent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
                localIntent.putExtra("app_package", context.getPackageName());
                localIntent.putExtra("app_uid", context.getApplicationInfo().uid);
                context.startActivity(localIntent);
                return;
            }

            //4.4以下没有从app跳转到应用通知设置页面的Action，可考虑跳转到应用详情页面,

            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
            context.startActivity(localIntent);
        } catch (Exception e) {
            e.printStackTrace();
            toSetting(context);
        }
    }

    public static void toSetting(Context context) {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", context.getPackageName(), null);
        intent.setData(uri);
        context.startActivity(intent);
    }

    public static String getMeizuFlymeOSFlag() {
        return getSystemProperty("ro.build.display.id", "");
    }

    private static String getSystemProperty(String key, String defaultValue) {
        try {
            Class<?> clz = Class.forName("android.os.SystemProperties");
            Method get = clz.getMethod("get", String.class, String.class);
            return (String) get.invoke(clz, key, defaultValue);
        } catch (Exception e) {
        }
        return defaultValue;
    }

    private static AlertDialog sSleepDialog;

    //课程休眠
    public static void showSleepDialog(byte b) {
        String sleepHex = Utils.bytesToHexString(new byte[]{b}).replaceAll(" ", "");
        int sleep = Integer.parseInt(sleepHex, 16);
        if (sleep != 3) {
            return;
        }
        final Activity activity = MyApplication.getActivityManager().currentActivity();
        if (sSleepDialog != null) {
            if (sSleepDialog.isShowing()) {
                return;
            }
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder
                .setCancelable(false)
                .setTitle(activity.getResources().getString(R.string.kindly_reminder_))
                .setMessage(activity.getResources().getString(R.string.device_sleep))
                .setPositiveButton(activity.getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        sSleepDialog = null;
                    }
                });
        sSleepDialog = builder.create();
        if (!sSleepDialog.isShowing()) {
            sSleepDialog.show();
        }
    }

}
